<template>
  <div
    class="app-gradient min-h-[480px] bg-gradient-to-b from-[#d7efff] via-[#eef7ff] to-white">
    <header
      class="app__header p-2 border-b border-[var(--border)] bg-transparent">
      <div class="app__brand font-semibold">多功能计算器</div>
      <div class="app__controls flex gap-2 items-center">
        <!-- <el-button
        id="themeToggle"
        class="btn bg-[var(--surface)] text-[var(--fg)] border border-[var(--border)] px-2 py-1 rounded-lg hover:border-[var(--accent)]"
        @click="toggleTheme"
        title="切换主题">
        🌓
      </el-button> -->
        <!-- <a
        class="btn bg-[var(--surface)] text-[var(--fg)] border border-[var(--border)] px-2 py-1 rounded-lg hover:border-[var(--accent)]"
        href="options.html"
        target="_blank"
        title="Options"
        >⚙️</a
      > -->
      </div>
    </header>

    <div
      class="max-w-[340px] overflow-auto p-[12px] whitespace-nowrap hide-scrollbar"
      ref="tabsScroll"
      @wheel.prevent="onHorizontalWheel('tabsScroll', $event)">
      <el-radio-group
        class="inline-flex flex-nowrap pill-tabs"
        v-model="currentTab"
        size="default">
        <el-radio-button v-for="t in tabs" :key="t.key" :label="t.key">
          <div class="flex items-center">
            {{ t.label }}
            <el-tooltip
              :content="isFavorite(t.key) ? '取消常用' : '设为常用'"
              placement="top">
              <el-icon
                class="ml-[6px]"
                :class="{ 'is-fav': isFavorite(t.key) }"
                @click.stop="toggleFavorite(t.key)">
                <StarFilled v-if="isFavorite(t.key)" />
                <Star v-else />
              </el-icon>
            </el-tooltip>
          </div>
        </el-radio-button>
      </el-radio-group>
    </div>
    <!-- 常用快捷入口 -->
    <div
      class="max-w-[340px] px-[12px]"
      v-if="favorites.length"
      ref="favScroll">
      <div class="mb-2 font-semibold">常用：</div>
      <span class="fav-wrap flex flex-wrap">
        <el-button
          v-for="fav in favorites"
          :key="fav"
          size="default"
          class="inline-flex items-center mr-2 mb-2"
          @click="currentTab = fav">
          {{ findLabel(fav) }}
          <el-icon class="ml-[6px]" @click.stop="toggleFavorite(fav)"
            ><StarFilled
          /></el-icon>
        </el-button>
      </span>
    </div>

    <main class="panes">
      <section v-show="currentTab === 'basic'">
        <Basic />
      </section>
      <!-- <section class="pane" data-pane="scientific">
      <div id="scientificCalculator"></div>
    </section>
    <section class="pane" data-pane="currency">
      <div id="currencyConverter"></div>
    </section>
    <section class="pane" data-pane="units">
      <div id="unitConverter"></div>
    </section> -->
      <section v-show="currentTab === 'compound'">
        <Compound />
      </section>
      <section v-show="currentTab === 'bmi'">
        <BMI />
      </section>
      <section v-show="currentTab === 'date'">
        <Date />
      </section>
      <section v-show="currentTab === 'increaseRate'">
        <IncreaseRate />
      </section>
      <section v-show="currentTab === 'unitPrice'">
        <UnitPrice />
      </section>
      <section v-show="currentTab === 'angle'">
        <AngleConvert />
      </section>
      <section v-show="currentTab === 'currency'">
        <Currency />
      </section>
      <section v-show="currentTab === 'color'">
        <Color />
      </section>
      <section v-show="currentTab === 'age'">
        <Age />
      </section>
      <!-- <section class="pane" data-pane="dates">
      <div id="dateCalculator"></div>
    </section> -->
    </main>
  </div>
</template>

<style>
@import "./assets/styles/popup.css";
@import "flag-icons/css/flag-icons.min.css";
</style>

<script setup lang="ts">
import { onMounted, reactive, ref, toRaw, watch } from "vue"

import "element-plus/dist/index.css"

import { Star, StarFilled } from "@element-plus/icons-vue"
import {
  ElButton,
  ElIcon,
  ElRadioButton,
  ElRadioGroup,
  ElTooltip
} from "element-plus"

// @ts-ignore - SFC default export by Vue plugin
import Age from "./components/Age.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import AngleConvert from "./components/AngleConvert.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import Basic from "./components/Basic.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import BMI from "./components/BMI.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import Color from "./components/Color.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import Compound from "./components/Compound.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import Currency from "./components/Currency.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import Date from "./components/Date.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import IncreaseRate from "./components/IncreaseRate.vue"
// @ts-ignore - SFC default export provided by Vue plugin
import UnitPrice from "./components/UnitPrice.vue"
import type { CalculatorType } from "./popup"
import { applyTheme, getSettings, setSettings } from "./scripts/settings.js"

// plugin will be installed via defineOptions.prepare below

const currentLang = ref<"en" | "zh">("en")
const currentTab = ref<CalculatorType>("basic")
const settings = ref<any>()
const tabs = ref<Array<{ key: CalculatorType; label: string }>>([
  { key: "basic", label: "基础" },
  { key: "compound", label: "复利" },
  { key: "bmi", label: "BMI" },
  { key: "date", label: "日期" },
  { key: "increaseRate", label: "增长率" },
  { key: "unitPrice", label: "单价" },
  { key: "age", label: "年龄" },
  { key: "angle", label: "角度" },
  { key: "currency", label: "汇率" },
  { key: "color", label: "颜色" }
])
const favorites = ref<CalculatorType[]>([])

function isFavorite(key: CalculatorType) {
  return favorites.value.includes(key)
}

function findLabel(key: CalculatorType) {
  return tabs.value.find((t) => t.key === key)?.label ?? key
}

async function toggleFavorite(key: CalculatorType) {
  const idx = favorites.value.indexOf(key)
  if (idx >= 0) {
    favorites.value.splice(idx, 1)
  } else {
    favorites.value.push(key)
  }
  await saveUserPrefs()
}

async function init() {
  settings.value = await getSettings()
  applyTheme(settings.value.theme, settings.value.accentColor)
  currentLang.value = settings.value.language
  const fav = settings.value?.favorites
  if (Array.isArray(fav)) {
    const allowed = new Set(tabs.value.map((t) => t.key))
    favorites.value = fav.filter((k: any) => allowed.has(k)) as CalculatorType[]
  }
  const lastTab = settings.value?.lastTab as CalculatorType | undefined
  if (lastTab && tabs.value.some((t) => t.key === lastTab)) {
    currentTab.value = lastTab
  }
}

onMounted(() => {
  init()
})

async function toggleTheme() {
  settings.value = await getSettings()
  const next = document.documentElement.classList.contains("theme-light")
    ? "dark"
    : "light"
  applyTheme(next, settings.value.accentColor)
}

// Persist currentTab when changed
watch(
  () => currentTab.value,
  async (val) => {
    await setSettings({ lastTab: val })
  }
)

// Horizontal wheel scroll helpers
const tabsScroll = ref<HTMLElement | null>(null)
const favScroll = ref<HTMLElement | null>(null)
function onHorizontalWheel(refName: "tabsScroll" | "favScroll", e: WheelEvent) {
  const el = refName === "tabsScroll" ? tabsScroll.value : favScroll.value
  if (!el) return
  el.scrollLeft += e.deltaY
}

// Persist favorites and lastTab together to avoid race overwrites
async function saveUserPrefs() {
  const favPlain = Array.from(toRaw(favorites.value || [])) // or [...favorites.value]
  await setSettings({
    favorites: favPlain,
    lastTab: currentTab.value
  })
}

watch(
  () => currentTab.value,
  async () => {
    await saveUserPrefs()
  }
)
</script>
